﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using Amazon.S3;
using Amazon.S3.Model;
using System.Configuration;

namespace DatabaseBackup.Library
{
    public static class AmazonS3Handler
    {
        /// <summary>
        /// Sends a backup file to the S3 bucket
        /// </summary>
        /// <param name="fileName"></param>
        public static void TransferFile(string fileName)
        {
            try
            {
                using (AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(Helpers.AmazonKey, Helpers.AmazonSecret))
                {
                    PutObjectRequest request = new PutObjectRequest();

                    request.WithBucketName(Helpers.AmazonBucket)
                        .WithKey(Path.GetFileName(fileName))
                        .WithContentType("application/octet-stream")
                        .WithTimeout(-1)
                        .WithReadWriteTimeout(3000000)
                        .WithFilePath(fileName);

                    S3Response response = new S3Response();

                    try
                    {
                        response = client.PutObject(request);
                    }
                    catch (AmazonS3Exception ex)
                    {
                        ErrorHandler.AddToErrorLog(ex);
                    }
                    finally
                    {
                        response.Dispose();
                    }

                }
            }

            catch (Exception ex)
            {
                ErrorHandler.AddToErrorLog(ex);
            }
        }

        /// <summary>
        /// Cleans up old file that has passed its retention period
        /// </summary>
        /// <param name="type"></param>
        public static void RemoveFile(string fileName)
        {
            try
            {
                using (AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(Helpers.AmazonKey, Helpers.AmazonSecret))
                {
                    DeleteObjectRequest request = new DeleteObjectRequest();

                    request.WithBucketName(Helpers.AmazonBucket)
                        .WithKey(fileName);

                    S3Response response = new S3Response();

                    try
                    {
                        response = client.DeleteObject(request);
                    }
                    catch (AmazonS3Exception ex)
                    {
                        ErrorHandler.AddToErrorLog(ex);
                    }
                    finally
                    {
                        response.Dispose();
                    }
                }
            }

            catch (Exception ex)
            {
                ErrorHandler.AddToErrorLog(ex);
            }
        }
    }
}


